﻿/*****************************************************************************
Copyright (c) 2011 SmartVault, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
******************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;

namespace SmartVault.Core
{
    /// <summary>
    /// RelativePath
    /// 
    /// Provides a pathing class for easy handling of non host portion of a URI path.
    /// These paths are case insensitive.
    /// 
    /// This path is not rooted.
    /// 
    /// Example: My Account/Vault/Folder
    /// </summary>
    public class RelativePath : IPath
    {
        #region Private Members
        private string _path;
        private List<string> _elements = new List<string>();
        #endregion

        #region Constructor
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="path"></param>
        public RelativePath(string path)
        {
            if (string.IsNullOrEmpty(path)) throw new ArgumentException("path");
            if (path[0] == '/') throw new ArgumentException("path");

            if (path.Length > 1 && path[path.Length - 1] == '/')
            {
                path = path.Substring(0, path.Length - 1);
            }

            if (path.Length > 1)
            {
                int start = 0;
                int length = 0;

                for (int i = start; i < path.Length; ++i)
                {
                    if (path[i] == '/')
                    {
                        _elements.Add(path.Substring(start, length));
                        length = 0;
                        start = i + 1;
                    }
                    else
                    {
                        ++length;
                    }
                }
                _elements.Add(path.Substring(start, length));
            }

            _path = path;
        }

        internal RelativePath(IList<string> path, int startIndex, int count)
        {
            if (startIndex >= path.Count) throw new ArgumentOutOfRangeException();

            if (path.Count == 0) throw new ArgumentException("path");

            StringBuilder bld = new StringBuilder();
            for (int i = startIndex; i < startIndex + count; ++i)
            {
                if (string.IsNullOrEmpty(path[i])) throw new ArgumentException("path");

                if (i == startIndex)
                {
                    bld.Append(path[i]);
                }
                else
                {
                    bld.AppendFormat("/{0}", path[i]);
                }

                _elements.Add(path[i]);
            }

            _path = bld.ToString();

        }
        #endregion

        #region Public Properties
        /// <summary>
        /// Return Last Element
        /// </summary>
        public string Last
        {
            get
            {
                return this[Count - 1];
            }
        }

        /// <summary>
        /// Count
        /// </summary>
        public int Count
        {
            get
            {
                return _elements.Count;
            }
        }
        #endregion

        #region Public Methods
        /// <summary>
        /// Append Element
        /// </summary>
        /// <param name="element">Element to append</param>
        /// <returns></returns>
        public RelativePath Append(string element)
        {
            if (string.IsNullOrEmpty(element)) throw new ArgumentException("element");
            if (element[0] == '/') throw new ArgumentException("element");

            return new RelativePath(_path + '/' + element);
        }

        /// <summary>
        /// Append Relative Path
        /// </summary>
        /// <param name="path">Relative Path to Append</param>
        /// <returns></returns>
        public RelativePath Append(RelativePath rhs)
        {
            if (rhs == null) throw new ArgumentException("rhs");
            return new RelativePath(_path + '/' + rhs.ToString());
        }

        /// <summary>
        /// Convert to Absolute Path
        /// </summary>
        /// <returns></returns>
        public AbsolutePath ToAbsolute()
        {
            return new AbsolutePath(_elements, 0, _elements.Count);
        }

        IPath IPath.Append(string element)
        {
            return this.Append(element);
        }

        IPath IPath.Append(RelativePath rhs)
        {
            return this.Append(rhs);
        }

        /// <summary>
        /// Equal Operator
        /// </summary>
        /// <param name="lhs"></param>
        /// <param name="rhs"></param>
        /// <returns></returns>
        public static bool operator ==(RelativePath lhs, RelativePath rhs)
        {
            if (((object)lhs) == null) return ((object)rhs) == null;
            return lhs.Equals(rhs);
        }

        /// <summary>
        /// Not Equal Operator
        /// </summary>
        /// <param name="lhs"></param>
        /// <param name="rhs"></param>
        /// <returns></returns>
        public static bool operator !=(RelativePath lhs, RelativePath rhs)
        {
            return (!(lhs == rhs));
        }

        /// <summary>
        /// ToString()
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return _path;
        }

        /// <summary>
        /// Equals()
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public override bool Equals(object obj)
        {
            if (obj == null) return false;
            return obj.ToString().Equals(this.ToString());
        }

        /// <summary>
        /// GetHasCode
        /// </summary>
        /// <returns></returns>
        public override int GetHashCode()
        {
            return this.ToString().GetHashCode();
        }

        /// <summary>
        /// Indexer
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public string this[int index]
        {
            get
            {
                return _elements[index];
            }
        }

        /// <summary>
        /// Provide a subpath
        /// </summary>
        /// <param name="startIndex">Index to start at</param>
        /// <returns></returns>
        public RelativePath Subpath(int startIndex)
        {
            return new RelativePath(_elements, startIndex, _elements.Count - startIndex);
        }

        /// <summary>
        /// Provide a subpath
        /// </summary>
        /// <param name="startIndex">Index to start at</param>
        /// <returns></returns>
        public RelativePath Subpath(int startIndex, int length)
        {
            return new RelativePath(_elements, startIndex, length);
        }
        #endregion
    }
}
